import java.io.File;
import java.io.IOException;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.statistics.HistogramDataset;
import org.jfree.data.statistics.HistogramType;

/**
 * Responsible for creating charts.
 * @author Josh and Ted
 *
 */
public class ChartWrapper
{	
	private static ChartWrapper chartWrapper;
	
	private ChartWrapper()
	{}
	
	public static ChartWrapper GetInstance()
	{
		if (chartWrapper == null)
			chartWrapper = new ChartWrapper();
		return chartWrapper;
	}
	/**
	 * Creates a new Histogram.
	 * @param title - The title of the histogram.
	 * @param xAxisLabel - The X-Axis Label.
	 * @param yAxisLabel - The Y-Axis Label.
	 * @param values - The array of values.
	 * @param horizontal - Whether or not to use horizontal orientation.
	 * @param legend - Whether or not to display legend.
	 * @param comparable - The comparable to use for sorting bins.
	 * @param bins - The number of bins.
	 * @return The constructed JFreeChart.
	 */
	public void CreateRelativeHistogram(String title, String xAxisLabel,
			String yAxisLabel, ChartVersion[] chartVersions, boolean horizontal,
			boolean legend, boolean relative)
	{
		HistogramDataset dataset = new HistogramDataset();
		
		for (int i=0; i<chartVersions.length; i++)
		{
			dataset.addSeries(chartVersions[i].getVersion().getIdentifier(), chartVersions[i].getSeriesData(),
					chartVersions[i].getBinCount(), chartVersions[i].getBinMin(),
					chartVersions[i].getBinMax());
			
			if (relative)
				dataset.setType(HistogramType.RELATIVE_FREQUENCY);

			//Write the histogram data to the text file
			RocketTools.writeToTextFile(chartVersions[i],"histogram.txt");
		}

		PlotOrientation orientation;
		if (horizontal)
			orientation = PlotOrientation.HORIZONTAL;
		else
			orientation = PlotOrientation.VERTICAL;

		JFreeChart chart = ChartFactory.createHistogram(title, xAxisLabel,
				yAxisLabel, dataset, orientation, legend, false, false);
         
		File f = new File(title + ".jpg");
         try {
			ChartUtilities.saveChartAsJPEG(f, chart, 400,400);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

